package service

import (
	"errors"
	"fmt"
	"gin-chat/entity"
	"gin-chat/models"
	"gin-chat/pkg"
	"gin-chat/router/request"
	"gin-chat/util"
)

func Register(uuid int64, params *request.RegisterRequest) error {
	mgr := models.CUserMgr()
	//1.验证邮件是否已被注册
	existed, _ := mgr.GetFromEmail(params.Email)
	if existed.ID != 0 {
		fmt.Println("existed", existed)
		return errors.New("该邮箱已注册")
	}
	user := entity.CUser{
		UUID:     uuid,
		Nickname: params.NickName,
		Password: util.Md5String(params.Password),
		Email:    params.Email,
	}
	err := mgr.InsertData(user)
	if err != nil {
		return err
	}
	return nil
}

func Login(params *request.LoginRequest) (*entity.CUser, int) {
	mgr := models.CUserMgr()
	uuid, _ := mgr.GetFromUUID(params.UUID)
	if uuid.ID == 0 {
		return &uuid, pkg.UserNoExistent
	}
	if util.Md5String(params.Password) != uuid.Password {
		return &uuid, pkg.PasswordErr
	}
	return &uuid, 0
}
